package com.ruoyi.web.controller.ring.app;

import cn.hutool.core.convert.Convert;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.ring.domain.RingSportRecord;
import com.ruoyi.ring.domain.dto.RingSportRecordAddDTO;
import com.ruoyi.ring.service.IRingSportRecordService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 运动 （APP）
 */
@RestController
@RequestMapping("/ring/app/ring_sport_record")
public class AppSportRecordController extends BaseController
{
    @Resource
    private IRingSportRecordService ringSportRecordService;


    @GetMapping("/latest")
    public AjaxResult latest(RingSportRecord ringSportRecord)
    {
        RingSportRecord record = ringSportRecordService.selectOneRingSportRecord(ringSportRecord);
        return AjaxResult.success(record);
    }

    /**
     * 上报运动信息 app
     */
    @PostMapping("/add")
    public AjaxResult addRecord(@RequestBody RingSportRecordAddDTO addDTO)
    {
        String deviceSn = addDTO.getDeviceSn();
        try {
            List<RingSportRecordAddDTO.StressDTO> stressDTOList = addDTO.getStress();
            stressDTOList.forEach(stressDTO -> {
                Date dailyValue = stressDTO.getDailyValue();
                RingSportRecord sportRecord = ringSportRecordService.selectOneRingSportRecord(Builder.of(RingSportRecord::new).
                        with(RingSportRecord::setDeviceSn, deviceSn).
                        with(RingSportRecord::setDailyValue, dailyValue).build());
                RingSportRecord ringSportRecord = Convert.convert(RingSportRecord.class,stressDTO);
                if(sportRecord != null){
                    ringSportRecord.setId(sportRecord.getId());
                    ringSportRecord.setDeviceSn(deviceSn);
                    ringSportRecordService.updateRingSportRecord(ringSportRecord);
                }else {
                    ringSportRecord.setDeviceSn(deviceSn);
                    ringSportRecordService.insertRingSportRecord(ringSportRecord);
                }
            });
            return AjaxResult.success();
        }catch (Exception e){
            throw new RuntimeException("上报运动信息失败！");
        }
    }

}
